import json
import re

import requests
from requests import utils

from unit_tools.handle_data.yaml_handler import read_yaml, write_yaml
from unit_tools.log_util.recordlog import logs


class SendRequests:

    def __init__(self):
        pass

    @classmethod
    def _text_encode(cls, res_text):
        """
        处理接口返回值出现unicode编码时，如：\\u767b
        :param res_text:
        :return:
        """
        match = re.search(r"\\u[0-9a-fA-F]{4}", res_text)
        if match:
            result = res_text.encode().decode('unicode_escape')
        else:
            result = res_text
        return result

    def send_request(self, **kwargs):
        # 创建一个会话
        session = requests.Session()
        response = None
        try:
            response = session.request(**kwargs)
            set_cookie = requests.utils.dict_from_cookiejar(response.cookies)
            if set_cookie:
                write_yaml({'Cookie': set_cookie})
            res = self._text_encode(response.text)
        except requests.exceptions.ConnectionError:
            logs.error('接口请求异常，可能是request的链接数过多或者速度过快导致程序报错！')
        except requests.exceptions.RequestException as e:
            logs.error(f'请求异常，请检查系统或数据是否正常！原因：{e}')

        return response

    def execute_api_request(self, api_name, url, method, headers, case_name, cookies=None, files=None, **kwargs):
        """
        发起接口请求
        :param api_name: 接口名称
        :param url: 接口地址
        :param method: 请求方法
        :param headers: 请求头
        :param case_name: 测试用例名称
        :param cookies: cookie
        :param files: 文件上传
        :param kwargs: 未知数量的关键字参数
        :return:
        """
        logs.info(f'接口名称：{api_name}')
        logs.info(f'请求地址：{url}')
        logs.info(f'请求方式：{method.upper()}')
        logs.info(f'请求头：{headers}')
        logs.info(f'测试用例名：{case_name}')
        logs.info(f'cookies值：{cookies}')

        yaml_params_type = kwargs.keys()
        if kwargs and ('data' in yaml_params_type or 'json' in yaml_params_type or 'params' in yaml_params_type):
            params_type = list(kwargs.keys())[0]
            logs.info(f'参数类型：{params_type}')
            params = json.dumps(list(kwargs.values())[0], ensure_ascii=False)
            logs.info(f'请求参数：{params}')

        response = self.send_request(method=method,
                                     url=url,
                                     headers=headers,
                                     cookies=cookies,
                                     files=files,
                                     timeout=10,
                                     verify=False,
                                     **kwargs)
        return response


if __name__ == '__main__':
    from unit_tools.handle_data.configParse import ConfigParse

    host = ConfigParse().get_host('host')
    data = read_yaml('.././data/login.yaml')[0]
    #url = host + data['baseInfo']['url']
    url=host+data[0]['url']
    #method = data['baseInfo']['method']
    method=data[0]['method']
    # header = data['baseInfo']['header']
    #header = None
    #req_data = data['testCase'][0]['data']
    req_data=data[1]['data']
    send = SendRequests()

    headers={
        'User-Agent':'Apifox/1.0.0 (https://apifox.com)',
        'Content-Type':'application/x-www-form-urlencoded',
    }
    res = send.execute_api_request(api_name=None, url=url, method=method, headers=headers, case_name=None,
                                   data=req_data)
    res_json = res.json()
    print(res_json)
    token = res_json['token']
    user_id = res_json['userId']
    write_yaml({'token': token, 'userId': user_id})
